from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Side, Border, PatternFill, GradientFill

workbook = Workbook()
sheet = workbook.active
# 1. 设置字体样式
cell = sheet['A1']
font = Font(name='微软雅黑', size=12, bold=True, italic=True, color="FF0000")
cell.value = '样式'
cell.font = font

# 2. 设置对齐样式
# 水平对齐:distributed, justify, center, left, fill, centerContinuous, right, general
# 垂直对齐:bottom, distributed, justify, center, top
cell = sheet['A2']
alignment = Alignment(horizontal='center', vertical='center', textRotation=45, wrapText=True)
cell.value = 'dfjkl;asdkjfadsfk;lasdjf;asjdf;lasdf'
cell.alignment = alignment

# 3. 设置边框样式
# 边线样式:double, mediumDashDotDot, slantDashDot, dashDotDot, dotted, hair,
# mediumDashed, dashed, dashDot, thin, mediumDashDot, medium, thick
cell = sheet['A1']
side = Side(style='thin', color='FF0000')
border = Border(left=side, right=side, top=side, bottom=side)
cell.border = border

# 4. 设置单元格填充样式
cell = sheet['A3']
pattern_fill = PatternFill(fill_type='solid', fgColor='99CCFF')
cell.fill = pattern_fill
cell2 = sheet['A4']
gfill = GradientFill(stop=('FFFFFF', '99ccff', '000000',))
cell2.fill = gfill

# 5. 设置行高和列宽
sheet.row_dimensions[1].height = 50
sheet.column_dimensions['C'].width = 20

# 6. 单元格合并与取消
sheet.merge_cells('A1:B2')
sheet.merge_cells(start_row=1, start_column=3, end_row=2, end_column=4)
sheet.unmerge_cells('A1:B2')
sheet.unmerge_cells(start_row=1, start_column=3, end_row=2, end_column=4)
workbook.save(filename='测试样式设置.xlsx')
